<template>
  <div class="import-questions-manual">
    <TeacherNavbar title="手动导入题库" />
    
    <el-form :model="form" label-width="120px" @submit.prevent="handleSubmit">
      <!-- 题目列表 -->
      <el-form-item label="题目列表">
        <el-table :data="questions" style="width: 100%; margin-bottom: 20px;">
          <el-table-column prop="questionType" label="题型" width="80">
            <template #default="scope">
              <el-tag v-if="scope.row.questionType === 'choice'">选择题</el-tag>
              <el-tag v-else-if="scope.row.questionType === 'judgment' || scope.row.questionType === 'judgement'">判断题</el-tag>
              <el-tag v-else-if="scope.row.questionType === 'fill'">填空题</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="questionContent" label="题目内容" width="400"></el-table-column>
          <el-table-column prop="answer" label="答案" width="150"></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="danger" @click="removeQuestion(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 添加新题目按钮 -->
        <el-button type="primary" @click="showAddQuestionDialog">添加题目</el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">导入</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 添加题目对话框 -->
    <el-dialog v-model="dialogVisible" title="添加题目" width="600px">
      <el-form :model="currentQuestion" :rules="questionRules" ref="questionForm" label-width="80px">
        <el-form-item label="题型" prop="questionType">
          <el-select v-model="currentQuestion.questionType" placeholder="请选择题型">
            <el-option label="选择题" value="choice"></el-option>
            <el-option label="判断题" value="judgment"></el-option>
            <el-option label="填空题" value="fill"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="题目内容" prop="questionContent">
          <el-input 
            v-model="currentQuestion.questionContent" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入题目内容，选项等">
          </el-input>
        </el-form-item>
        
        <el-form-item label="答案" prop="answer">
          <el-input 
            v-model="currentQuestion.answer" 
            placeholder="请输入正确答案"
            v-if="currentQuestion.questionType !== 'choice'">
          </el-input>
          <el-select 
            v-model="currentQuestion.answer" 
            placeholder="请选择正确答案"
            v-else>
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addQuestion">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import TeacherAPI from '@/api/teacher'
import TeacherNavbar from '@/components/TeacherNavbar.vue'

export default {
  name: 'ImportQuestionsManual',
  components: {
    TeacherNavbar
  },
  data() {
    // 验证答案是否符合要求
    const validateAnswer = (rule, value, callback) => {
      if (!value) {
        callback(new Error('答案不能为空'));
        return;
      }
      
      // 根据题型验证答案
      if (this.currentQuestion.questionType === 'choice') {
        if (!['A', 'B', 'C', 'D'].includes(value)) {
          callback(new Error('选择题答案必须是A、B、C、D中的一个'));
          return;
        }
      } else if (this.currentQuestion.questionType === 'judgment') {
        if (value !== '0' && value !== '1') {
          callback(new Error('判断题答案必须是0（错误）或1（正确）'));
          return;
        }
      } else if (this.currentQuestion.questionType === 'fill') {
        if (!value.trim()) {
          callback(new Error('填空题答案不能为空'));
          return;
        }
      }
      
      callback();
    };
    
    return {
      form: {
        subjectId: '',
        questions: []
      },
      subjectList: [],
      questions: [],
      dialogVisible: false,
      currentQuestion: {
        questionType: 'choice',
        questionContent: '',
        answer: ''
      },
      questionRules: {
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        questionContent: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' },
          { validator: validateAnswer, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 从路由参数获取科目ID
    const subjectId = this.$route.query.subjectId
    if (subjectId) {
      this.form.subjectId = parseInt(subjectId)
    }
  },
  methods: {
    // 显示添加题目对话框
    showAddQuestionDialog() {
      this.currentQuestion = {
        questionType: 'choice',
        questionContent: '',
        answer: ''
      }
      this.dialogVisible = true
    },

    // 添加新题目
    addQuestion() {
      this.$refs.questionForm.validate((valid) => {
        if (valid) {
          // 添加题目到列表
          this.questions.push({
            ...this.currentQuestion
          })
          
          // 关闭对话框
          this.dialogVisible = false
        } else {
          this.$message.error('请填写完整且正确的题目信息')
          return false
        }
      })
    },

    // 删除题目
    removeQuestion(index) {
      this.questions.splice(index, 1)
    },

    // 提交导入
    async handleSubmit() {
      // 验证表单
      if (!this.form.subjectId) {
        this.$message.error('科目信息不正确')
        return
      }
      
      if (this.questions.length === 0) {
        this.$message.error('请至少添加一个题目')
        return
      }
      
      // 检查每个题目的必填项
      for (let i = 0; i < this.questions.length; i++) {
        const question = this.questions[i];
        if (!question.questionType || !question.questionContent || !question.answer) {
          this.$message.error(`第${i+1}个题目信息不完整`) 
          return
        }
        
        // 验证答案格式
        if (question.questionType === 'choice' && !['A', 'B', 'C', 'D'].includes(question.answer)) {
          this.$message.error(`第${i+1}个选择题答案必须是A、B、C、D中的一个`)
          return
        } else if (question.questionType === 'judgment' && question.answer !== '0' && question.answer !== '1') {
          this.$message.error(`第${i+1}个判断题答案必须是0（错误）或1（正确）`)
          return
        } else if (question.questionType === 'fill' && !question.answer.trim()) {
          this.$message.error(`第${i+1}个填空题答案不能为空`)
          return
        }
      }
      
      try {
        // 逐个导入题目
        let successCount = 0;
        for (const question of this.questions) {
          // 构造单个题目请求数据
          const questionData = {
            questionType: question.questionType,
            subjectId: this.form.subjectId,
            questionContent: question.questionContent,
            answer: question.answer
          };
          
          // 发起导入请求
          const res = await TeacherAPI.importQuestionsManual(questionData);
          if (res.data.code === 200 && res.data.msg === 'success') {
            successCount++;
          } else {
            this.$message.error(`题目"${question.questionContent.substring(0, 20)}..."导入失败: ` + (res.data.data || res.data.message));
            return;
          }
        }
        
        this.$message.success(`成功导入${successCount}道题目`);
        // 返回科目列表
        this.$router.push('/teacher/subjects');
      } catch (error) {
        console.error('导入题目失败:', error);
        this.$message.error('导入题目失败: ' + (error.response?.data?.message || error.message));
      }
    },

    // 取消操作
    handleCancel() {
      this.$router.push('/teacher/subjects');
    }
  }
}
</script>

<style scoped>
.import-questions-manual {
  padding: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>